<template>
  <div 
    class="chat-panel" 
    :class="{ 
      'expanded': isExpanded, 
      'minimized': isMinimized,
      'mobile': isMobile 
    }"
  >
    <!-- 聊天头部 -->
    <div class="chat-header" @click="toggleMinimize">
      <span class="chat-title">
💬 {{ isStoryteller ? '说书人聊天' : '与说书人聊天' }}
        <span v-if="totalUnreadCount > 0" class="unread-badge">{{ totalUnreadCount }}</span>
      </span>
      <div class="chat-controls" @click.stop>
        <button @click="toggleExpand" class="control-btn" :title="isExpanded ? '收起' : '展开'">
          {{ isExpanded ? '−' : '+' }}
        </button>
        <button @click="toggleMinimize" class="control-btn" :title="isMinimized ? '展开' : '收起'">
          {{ isMinimized ? '▲' : '▼' }}
        </button>
      </div>
    </div>

    <!-- 聊天内容区 -->
    <div class="chat-content" v-show="!isMinimized">
      <!-- 玩家标签页 -->
      <div class="chat-tabs" v-if="availablePlayers.length > 0">
        <div 
          v-for="player in availablePlayers" 
          :key="player.id"
          :class="[
            'chat-tab', 
            { 
              active: activeTab === player.id, 
              unread: hasUnread(player.id) 
            }
          ]"
          @click="switchToPlayer(player.id)"
        >
          <span class="player-name" @click.stop="switchToPlayer(player.id)">{{ player.name }}</span>
          <span v-if="hasUnread(player.id)" class="unread-count">{{ getUnreadCount(player.id) }}</span>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="availablePlayers.length === 0" class="empty-state">
        <p v-if="isStoryteller">🎭 等待玩家加入游戏...</p>
        <p v-else>⏳ 等待连接到说书人...</p>
      </div>

      <!-- 消息列表 -->
      <div 
        v-if="activeTab" 
        class="message-list" 
        ref="messageList"
        @scroll="handleScroll"
      >
        <div v-if="currentMessages.length === 0" class="no-messages">
          <p v-if="isStoryteller">💬 开始与 {{ activePlayerName }} 聊天吧！</p>
          <p v-else>💬 开始与说书人聊天吧！</p>
        </div>
        <div 
          v-for="message in currentMessages" 
          :key="message.id"
          :class="[
            'message', 
            { 
              'own-message': message.isStoryteller === isStoryteller, 
              'other-message': message.isStoryteller !== isStoryteller,
              'unread': !message.isRead
            }
          ]"
        >
          <div class="message-bubble">
            <div class="message-sender" v-if="message.isStoryteller !== isStoryteller">
              {{ getSenderName(message) }}
            </div>
            <div class="message-content">
              {{ message.content }}
            </div>
            <div class="message-time">
              {{ formatTime(message.timestamp) }}
            </div>
          </div>
        </div>
      </div>

      <!-- 消息输入 -->
      <div v-if="activeTab" class="message-input">
        <div class="input-container">
          <input 
            v-model="newMessage" 
            @keydown.enter="sendMessage"
            @input="handleInput"
            :placeholder="isStoryteller ? `给 ${activePlayerName} 发消息...` : '给说书人发消息...'"
            :disabled="!activeTab || isSending"
            class="message-input-field"
            maxlength="500"
          />
          <button 
            @click="sendMessage" 
            :disabled="!canSendMessage"
            class="send-btn"
            :class="{ sending: isSending }"
          >
            {{ isSending ? '...' : '发送' }}
          </button>
        </div>
        <div class="input-info">
          <span class="char-count" :class="{ warning: newMessage.length > 400 }">
            {{ newMessage.length }}/500
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';

export default {
  name: 'ChatPanel',
  data() {
    return {
      isExpanded: false,
      isMinimized: false,  // 默认显示聊天面板，不要最小化
      activeTab: null,
      newMessage: '',
      isSending: false,
      autoScroll: true,
      isMobile: false
    };
  },
  computed: {
    ...mapState(['grimoire']),
    ...mapState('session', ['sessionId']),
    ...mapState('players', ['players']),
    
    // 聊天状态
    ...mapState('chat', ['privateMessages', 'unreadCounts']),
    
    // 检查是否为说书人
    isStoryteller() {
      return !this.$store.state.session.isSpectator;
    },
    
    // 可用聊天对象列表
    availablePlayers() {
      if (this.isStoryteller) {
        // 说书人：可以和所有玩家聊天
        const validPlayers = this.players.filter(player => player.id && player.name);

        return validPlayers;
      } else {
        // 玩家：只能和说书人聊天
        return [{ id: 'storyteller', name: '说书人' }];
      }
    },
    
    // 当前活跃玩家名称
    activePlayerName() {
      const player = this.availablePlayers.find(p => p.id === this.activeTab);
      return player ? player.name : '';
    },
    
    // 当前聊天消息  
    currentMessages() {
      if (!this.activeTab) return [];
      
      // 强制检查最新数据
      const latestMessages = this.$store.state.chat.privateMessages;
      const messages = latestMessages[this.activeTab] || [];
      

      
      return messages;
    },
    
    // 总未读数量
    totalUnreadCount() {
      return Object.values(this.unreadCounts).reduce((sum, count) => sum + count, 0);
    },
    
    // 是否可以发送消息
    canSendMessage() {
      return this.newMessage.trim().length > 0 && !this.isSending && this.activeTab;
    }
  },
  watch: {
    // 监听玩家变化，自动选择第一个玩家
    availablePlayers: {
      handler(newPlayers) {
        if (newPlayers.length > 0 && !this.activeTab) {
          this.activeTab = newPlayers[0].id;
        } else if (newPlayers.length === 0) {
          this.activeTab = null;
        }
        
        // 检查当前activeTab是否仍然有效
        if (this.activeTab && !newPlayers.find(p => p.id === this.activeTab)) {
          this.activeTab = newPlayers.length > 0 ? newPlayers[0].id : null;
        }
      },
      immediate: true
    },
    
    // 监听当前消息变化，自动滚动
    currentMessages: {
      handler() {
        if (this.autoScroll) {
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        }
      },
      deep: true
    },
    
    // 强制监听privateMessages变化
    privateMessages: {
      handler() {
        // Vue响应式更新触发
      },
      deep: true
    },
    
    // 监听活跃标签变化，标记为已读
    activeTab(newTab, oldTab) {
      if (newTab) {
        this.markMessagesAsRead(newTab);
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
      
      // 清除旧标签的未读计数
      if (oldTab && oldTab !== newTab) {
        this.$store.commit('chat/clearUnread', oldTab);
      }
    }
  },
  mounted() {
    
    this.checkMobile();
    window.addEventListener('resize', this.checkMobile);
    
    // 延迟初始化activeTab，确保玩家数据已加载
    this.$nextTick(() => {
      if (this.availablePlayers.length > 0 && !this.activeTab) {
        this.activeTab = this.availablePlayers[0].id;

      }
    });
    
    // 初始化聊天模块
    if (!this.$store.state.chat) {
      console.warn('❌ Chat module not found in store');
    } else {
      console.log('✅ Chat module initialized successfully');
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.checkMobile);
  },
  methods: {
    
    // 检测移动端
    checkMobile() {
      this.isMobile = window.innerWidth <= 768;
      if (this.isMobile && this.isExpanded) {
        this.isExpanded = false; // 移动端不使用扩展模式
      }
    },
    
    // 切换展开状态
    toggleExpand() {
      if (!this.isMobile) {
        this.isExpanded = !this.isExpanded;
      }
    },
    
    // 切换最小化状态
    toggleMinimize() {
      this.isMinimized = !this.isMinimized;
      if (!this.isMinimized && this.activeTab) {
        this.markMessagesAsRead(this.activeTab);
      }
    },
    
    // 切换到指定玩家
    switchToPlayer(playerId) {
      this.activeTab = playerId;
      
      // 立即清除新标签的未读计数
      this.$store.commit('chat/clearUnread', playerId);
      
      // 标记消息为已读
      this.markMessagesAsRead(playerId);
    },
    
    // 检查是否有未读消息
    hasUnread(playerId) {
      return (this.unreadCounts[playerId] || 0) > 0;
    },
    
    // 获取未读数量
    getUnreadCount(playerId) {
      return this.unreadCounts[playerId] || 0;
    },
    
    // 标记消息为已读
    markMessagesAsRead(playerId) {
      if (this.hasUnread(playerId)) {
        this.clearUnread(playerId);
        // 标记所有消息为已读
        const messages = this.privateMessages[playerId] || [];
        messages.forEach(message => {
          if (!message.isRead && !message.isStoryteller) {
            this.markAsRead({ playerId, messageId: message.id });
          }
        });
      }
    },
    
    // 发送消息
    async sendMessage() {
      if (!this.canSendMessage) return;
      
      const content = this.newMessage.trim();
      const playerId = this.activeTab;
      
      this.isSending = true;
      
      try {
        // 创建消息对象
        const message = {
          id: 'msg_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
          content,
          senderId: this.isStoryteller ? 'storyteller' : this.$store.state.session.playerId,
          receiverId: this.isStoryteller ? playerId : 'storyteller',
          timestamp: Date.now(),
          isStoryteller: this.isStoryteller,
          isRead: true,
          chatType: 'private'
        };
        
        // 添加到本地存储 (使用聊天对象的ID作为key)
        const chatTargetId = this.isStoryteller ? playerId : 'storyteller';
        this.$store.commit('chat/addMessage', { playerId: chatTargetId, message });
        

        
        // 通过Socket发送
        const socket = this.$store.state.socket;
        const isSocketReady = socket && socket._socket && socket._socket.readyState === 1;
        

        
        if (isSocketReady) {
          
          const success = this.$store.state.socket.sendPrivateMessage({
            roomId: this.sessionId,
            ...message
          });
          
          if (!success) {
            console.warn('❌ 消息发送失败，可能网络连接有问题');
            // 显示重试提示
            this.$nextTick(() => {
              // 可以在这里添加重试按钮或提示
            });
          }
        } else {
          console.warn('❌ Socket连接未就绪');
        }
        
        // 清空输入框
        this.newMessage = '';
        
        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom();
        });
        
      } catch (error) {
        console.error('发送消息失败:', error);
        // 可以添加错误提示
      } finally {
        this.isSending = false;
      }
    },
    
    // 处理输入
    handleInput() {
      // 可以添加输入相关的逻辑，比如正在输入状态
    },
    
    // 处理滚动
    handleScroll() {
      const messageList = this.$refs.messageList;
      if (messageList) {
        const { scrollTop, scrollHeight, clientHeight } = messageList;
        // 检查是否滚动到底部附近
        this.autoScroll = scrollTop + clientHeight >= scrollHeight - 50;
      }
    },
    
    // 滚动到底部
    scrollToBottom() {
      const messageList = this.$refs.messageList;
      if (messageList) {
        messageList.scrollTop = messageList.scrollHeight;
      }
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp);
      const now = new Date();
      const diffMs = now - date;
      const diffMins = Math.floor(diffMs / 60000);
      const diffHours = Math.floor(diffMs / 3600000);
      const diffDays = Math.floor(diffMs / 86400000);
      
      if (diffMins < 1) return '刚刚';
      if (diffMins < 60) return `${diffMins}分钟前`;
      if (diffHours < 24) return `${diffHours}小时前`;
      if (diffDays < 7) return `${diffDays}天前`;
      
      return date.toLocaleString('zh-CN', {
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    
    // 获取发送者名称
    getSenderName(message) {
      if (message.isStoryteller) {
        return '说书人';
      } else {
        // 根据senderId找到玩家名称
        const player = this.players.find(p => p.id === message.senderId);
        return player ? player.name : '玩家';
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.chat-panel {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 320px;
  height: 380px;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 10px;
  box-shadow: 2px 2px 20px 1px #000;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  font-family: inherit;
  
  &.expanded {
    width: 500px;
    height: 600px;
  }
  
      &.minimized {
      height: 50px;
      overflow: hidden;
      
      .chat-content {
        display: none;
      }
      
      .chat-title {
        cursor: pointer;
      }
    }
  
  &.mobile {
    width: calc(100vw - 20px);
    max-width: 400px;
    right: 10px;
    bottom: 10px;
    
    &.expanded {
      width: calc(100vw - 20px);
      height: 70vh;
      max-height: 500px;
    }
  }
}

.chat-header {
  padding: 10px 15px;
  background: rgba(0, 0, 0, 0.4);
  border-radius: 10px 10px 0 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  user-select: none;
  
  .chat-title {
    color: white;
    font-weight: bold;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .unread-badge {
    background: #dc3545;
    color: white;
    font-size: 11px;
    padding: 2px 6px;
    border-radius: 8px;
    min-width: 16px;
    text-align: center;
  }
  
  .chat-controls {
    display: flex;
    gap: 4px;
    
    .control-btn {
      background: none;
      border: none;
      color: #fff;
      width: 24px;
      height: 24px;
      border-radius: 3px;
      cursor: pointer;
      font-size: 14px;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: background-color 0.3s;
      
      &:hover {
        background: rgba(255, 255, 255, 0.1);
      }
    }
  }
}

.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-tabs {
  display: flex;
  background: rgba(0, 0, 0, 0.3);
  border-bottom: 1px solid #333;
  overflow-x: auto;
  padding: 2px 0;
  
  // 优化滚动条
  &::-webkit-scrollbar {
    height: 6px;
  }
  
  &::-webkit-scrollbar-track {
    background: rgba(255, 255, 255, 0.1);
    border-radius: 3px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.4);
    border-radius: 3px;
    
    &:hover {
      background: rgba(255, 255, 255, 0.6);
    }
  }
  
  .chat-tab {
    padding: 10px 14px;
    cursor: pointer;
    border-right: 1px solid #333;
    white-space: nowrap;
    color: #bbb;
    font-size: 13px;
    display: flex;
    align-items: center;
    gap: 6px;
    min-width: 90px;
    justify-content: space-between;
    transition: all 0.2s ease;
    border-radius: 4px 4px 0 0;
    margin: 0 1px;
    position: relative;
    
    &:hover {
      background: rgba(255, 255, 255, 0.15);
      color: white;
      transform: translateY(-1px);
    }
    
    &.active {
      background: linear-gradient(135deg, rgba(255, 255, 255, 0.25), rgba(255, 255, 255, 0.15));
      color: white;
      border-bottom: 2px solid rgba(255, 255, 255, 0.8);
      font-weight: 500;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
      z-index: 1;
      
      &::before {
        content: '';
        position: absolute;
        bottom: -2px;
        left: 0;
        right: 0;
        height: 2px;
        background: linear-gradient(90deg, #4CAF50, #45a049);
        border-radius: 1px;
      }
    }
    
    &.unread {
      background: rgba(220, 53, 69, 0.4);
      color: white;
      animation: pulse-tab 2s infinite;
      
      &.active {
        background: linear-gradient(135deg, rgba(220, 53, 69, 0.6), rgba(220, 53, 69, 0.4));
      }
    }
    
    .player-name {
      flex: 1;
      text-overflow: ellipsis;
      overflow: hidden;
      cursor: pointer;
      user-select: none;
    }
    
    .unread-count {
      background: rgba(255, 255, 255, 0.9);
      color: #333;
      font-size: 10px;
      padding: 1px 4px;
      border-radius: 8px;
      min-width: 16px;
      text-align: center;
      font-weight: bold;
    }
  }
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-style: italic;
  text-align: center;
  padding: 20px;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
  background: rgba(255, 255, 255, 0.05);
  
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-track {
    background: rgba(255, 255, 255, 0.1);
    border-radius: 3px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.3);
    border-radius: 3px;
    
    &:hover {
      background: rgba(255, 255, 255, 0.5);
    }
  }
  
  .no-messages {
    color: #999;
    text-align: center;
    font-style: italic;
    padding: 40px 20px;
  }
  
  .message {
    margin-bottom: 12px;
    display: flex;
    width: 100%;
    
    &.own-message {
      justify-content: flex-end;
      
      .message-bubble {
        background: linear-gradient(135deg, #4CAF50, #45a049);
        color: white;
        border-radius: 18px 18px 4px 18px;
        max-width: 75%;
        
        .message-time {
          color: rgba(255, 255, 255, 0.8);
        }
      }
    }
    
    &.other-message {
      justify-content: flex-start;
      
      .message-bubble {
        background: rgba(255, 255, 255, 0.15);
        color: white;
        border-radius: 18px 18px 18px 4px;
        max-width: 75%;
        border: 1px solid rgba(255, 255, 255, 0.1);
        
        .message-time {
          color: rgba(255, 255, 255, 0.6);
        }
      }
    }
    
    .message-bubble {
      padding: 10px 14px;
      position: relative;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
      word-wrap: break-word;
      
      .message-sender {
        font-size: 11px;
        color: rgba(255, 255, 255, 0.7);
        margin-bottom: 4px;
        font-weight: 500;
      }
      
      .message-content {
        font-size: 14px;
        line-height: 1.4;
        margin-bottom: 4px;
      }
      
      .message-time {
        font-size: 10px;
        text-align: right;
        opacity: 0.8;
        font-style: italic;
      }
    }
    
    &.unread {
      animation: slideIn 0.3s ease-out;
    }
  }
}

.message-input {
  border-top: 1px solid #333;
  background: rgba(0, 0, 0, 0.3);
  padding: 12px;
  
  .input-container {
    display: flex;
    gap: 8px;
    margin-bottom: 4px;
  }
  
  .message-input-field {
    flex: 1;
    padding: 8px 12px;
    border: 1px solid #555;
    border-radius: 20px;
    background: rgba(255, 255, 255, 0.1);
    color: white;
    font-size: 13px;
    outline: none;
    
    &:focus {
      border-color: rgba(255, 255, 255, 0.3);
      background: rgba(255, 255, 255, 0.15);
    }
    
    &::placeholder {
      color: #999;
    }
    
    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }
  
  .send-btn {
    padding: 8px 16px;
    background: rgba(255, 255, 255, 0.2);
    color: white;
    border: 1px solid rgba(255, 255, 255, 0.3);
    border-radius: 20px;
    cursor: pointer;
    font-size: 13px;
    font-weight: bold;
    min-width: 60px;
    
    &:hover:not(:disabled) {
      background: rgba(255, 255, 255, 0.3);
    }
    
    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
    
    &.sending {
      opacity: 0.7;
    }
  }
  
  .input-info {
    display: flex;
    justify-content: flex-end;
    
    .char-count {
      font-size: 10px;
      color: #999;
      
      &.warning {
        color: #ff9800;
      }
    }
  }
}

// 动画效果
@keyframes pulse-tab {
  0%, 100% { 
    background: rgba(220, 53, 69, 0.4);
  }
  50% { 
    background: rgba(220, 53, 69, 0.6);
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式设计

// 移动端适配
@media (max-width: 768px) {
  .chat-panel {
    width: calc(100vw - 20px) !important;
    max-width: none;
    right: 10px;
    bottom: 10px;
    
    &.expanded {
      height: 70vh !important;
      max-height: 500px;
    }
    
    &.minimized {
      height: 45px;
    }
  }
  
  .chat-header {
    padding: 10px 12px;
    
    .chat-title {
      font-size: 13px;
    }
    
    .control-btn {
      width: 20px;
      height: 20px;
      font-size: 12px;
    }
  }
  
  .chat-tabs .chat-tab {
    font-size: 11px;
    padding: 6px 8px;
    min-width: 60px;
  }
  
  .message-list {
    padding: 8px;
    
    .message .message-content {
      max-width: 85%;
      padding: 6px 10px;
    }
    
    .message-text {
      font-size: 12px;
    }
    
    .message-time {
      font-size: 9px;
    }
  }
  
  .message-input {
    padding: 8px;
    
    .message-input-field {
      font-size: 12px;
      padding: 6px 10px;
    }
    
    .send-btn {
      font-size: 12px;
      padding: 6px 12px;
      min-width: 50px;
    }
  }
}

// 超小屏幕适配
@media (max-width: 480px) {
  .chat-panel {
    width: calc(100vw - 10px) !important;
    right: 5px;
    bottom: 5px;
    
    &.expanded {
      height: 80vh !important;
    }
  }
  
  .message-list .message {
    &.own .message-content {
      margin-left: 20px;
    }
    
    &.player .message-content {
      margin-right: 20px;
    }
  }
}
</style>